<template>
  <div class="detail-container">
    <div>
      <el-steps :active="order.status ? order.status + 1 : 1" finish-status="success" align-center>
        <el-step title="提交订单" :description="formatDateTime(order.createTime)"></el-step>
        <el-step title="支付订单" :description="formatDateTime(order.paymentTime)"></el-step>
        <el-step title="平台发货" :description="formatDateTime(order.deliveryTime)"></el-step>
        <el-step title="确认收货" :description="formatDateTime(order.receiveTime)"></el-step>
        <el-step title="完成评价" :description="formatDateTime(order.commentTime)"></el-step>
      </el-steps>
    </div>
    <el-card shadow="never" style="margin-top: 15px">
      <div class="operate-container">
        <i class="el-icon-warning color-danger" style="margin-left: 20px"></i>
        <span class="color-danger">当前订单状态：{{ order.status && ORDER_STATUS_DICT[order.status] }}</span>
        <div class="operate-button-container" v-show="order.status === 0">
          <el-button size="small" @click="showUpdateReceiverDialog">修改收货人信息</el-button>
          <el-button size="small" @click="showUpdateMoneyDialog">修改费用信息</el-button>
          <el-button size="small" @click="showMessageDialog">发送站内信</el-button>
          <el-button size="small" @click="showCloseOrderDialog">关闭订单</el-button>
          <el-button size="small" @click="showMarkOrderDialog">备注订单</el-button>
        </div>
        <div class="operate-button-container" v-show="order.status === 1">
          <el-button size="small" @click="showUpdateReceiverDialog">修改收货人信息</el-button>
          <el-button size="small" @click="showMessageDialog">发送站内信</el-button>
          <el-button size="small">取消订单</el-button>
          <el-button size="small" @click="showMarkOrderDialog">备注订单</el-button>
        </div>
        <div class="operate-button-container" v-show="order.status === 2 || order.status === 3">
          <el-button size="small" @click="showLogisticsDialog">订单跟踪</el-button>
          <el-button size="small" @click="showMessageDialog">发送站内信</el-button>
          <el-button size="small" @click="showMarkOrderDialog">备注订单</el-button>
        </div>
        <div class="operate-button-container" v-show="order.status === 4">
          <el-button size="small" @click="handleDeleteOrder">删除订单</el-button>
          <el-button size="small" @click="showMarkOrderDialog">备注订单</el-button>
        </div>
      </div>
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">基本信息</span>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="4" class="table-cell-title">订单编号</el-col>
          <el-col :span="4" class="table-cell-title">发货单流水号</el-col>
          <el-col :span="4" class="table-cell-title">用户账号</el-col>
          <el-col :span="4" class="table-cell-title">支付方式</el-col>
          <el-col :span="4" class="table-cell-title">订单来源</el-col>
          <el-col :span="4" class="table-cell-title">订单类型</el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="table-cell">{{ order.orderSn }}</el-col>
          <el-col :span="4" class="table-cell">暂无</el-col>
          <el-col :span="4" class="table-cell">{{ order.memberUsername }}</el-col>
          <el-col :span="4" class="table-cell">{{ order.payType && PAY_TYPE_DICT[order.payType] }}</el-col>
          <el-col :span="4" class="table-cell">{{ order.sourceType && ORDER_SOURCE_TYPE_DICT[order.sourceType] }}</el-col>
          <el-col :span="4" class="table-cell">{{ order.orderType && ORDER_TYPE_DICT[order.orderType] }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="table-cell-title">配送方式</el-col>
          <el-col :span="4" class="table-cell-title">物流单号</el-col>
          <el-col :span="4" class="table-cell-title">自动确认收货时间</el-col>
          <el-col :span="4" class="table-cell-title">订单可得优币</el-col>
          <el-col :span="4" class="table-cell-title">订单可得成长值</el-col>
          <el-col :span="4" class="table-cell-title">活动信息</el-col>
        </el-row>
        <el-row>
          <el-col :span="4" class="table-cell">{{ formatNull(order.deliveryCompany) }}</el-col>
          <el-col :span="4" class="table-cell">{{ formatNull(order.deliverySn) }}</el-col>
          <el-col :span="4" class="table-cell">{{ order.autoConfirmDay }}天</el-col>
          <el-col :span="4" class="table-cell">{{ order.integration }}</el-col>
          <el-col :span="4" class="table-cell">{{ order.growth }}</el-col>
          <el-col :span="4" class="table-cell">
            <el-popover placement="top-start" title="活动信息" width="200" trigger="hover" :content="order.promotionInfo">
              <template v-slot:reference>
                <span>{{ formatLongText(order.promotionInfo) }}</span>
              </template>
            </el-popover>
          </el-col>
        </el-row>
      </div>
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">收货人信息</span>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="6" class="table-cell-title">收货人</el-col>
          <el-col :span="6" class="table-cell-title">手机号码</el-col>
          <el-col :span="6" class="table-cell-title">邮政编码</el-col>
          <el-col :span="6" class="table-cell-title">收货地址</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">{{ order.receiverName }}</el-col>
          <el-col :span="6" class="table-cell">{{ order.receiverPhone }}</el-col>
          <el-col :span="6" class="table-cell">{{ order.receiverPostCode }}</el-col>
          <el-col :span="6" class="table-cell">{{ formatAddress }}</el-col>
        </el-row>
      </div>
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">商品信息</span>
      </div>
      <el-table ref="orderItemTable" height="100%" :data="order.orderItemList" style="width: 100%; margin-top: 20px" border>
        <el-table-column label="商品图片" width="120" align="center">
          <template #default="scope">
            <img :src="scope.row.productPic" style="height: 80px" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template #default="scope">
            <p>{{ scope.row.productName }}</p>
            <p>品牌：{{ scope.row.productBrand }}</p>
          </template>
        </el-table-column>
        <el-table-column label="价格/货号" width="120" align="center">
          <template #default="scope">
            <p>价格：￥{{ scope.row.productPrice }}</p>
            <p>货号：{{ scope.row.productSn }}</p>
          </template>
        </el-table-column>
        <el-table-column label="属性" width="120" align="center">
          <template #default="scope">
            {{ formatProductAttr(scope.row.productAttr) }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120" align="center">
          <template #default="scope">
            {{ scope.row.productQuantity }}
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120" align="center">
          <template #default="scope"> ￥{{ scope.row.productPrice * scope.row.productQuantity }} </template>
        </el-table-column>
      </el-table>
      <div style="float: right; margin: 20px">
        合计：<span class="color-danger">￥{{ order.totalAmount }}</span>
      </div>
      <div style="margin-top: 60px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">费用信息</span>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="6" class="table-cell-title">商品合计</el-col>
          <el-col :span="6" class="table-cell-title">运费</el-col>
          <el-col :span="6" class="table-cell-title">优惠券</el-col>
          <el-col :span="6" class="table-cell-title">积分抵扣</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">￥{{ order.totalAmount }}</el-col>
          <el-col :span="6" class="table-cell">￥{{ order.freightAmount }}</el-col>
          <el-col :span="6" class="table-cell">-￥{{ order.couponAmount }}</el-col>
          <el-col :span="6" class="table-cell">-￥{{ order.integrationAmount }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell-title">活动优惠</el-col>
          <el-col :span="6" class="table-cell-title">折扣金额</el-col>
          <el-col :span="6" class="table-cell-title">订单总金额</el-col>
          <el-col :span="6" class="table-cell-title">应付款金额</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">-￥{{ order.promotionAmount }}</el-col>
          <el-col :span="6" class="table-cell">-￥{{ order.discountAmount }}</el-col>
          <el-col :span="6" class="table-cell">
            <span class="color-danger">￥{{ orderTotal }}</span>
          </el-col>
          <el-col :span="6" class="table-cell">
            <span class="color-danger">￥{{ orderPayTotal }}</span>
          </el-col>
        </el-row>
      </div>
      <div style="margin-top: 20px">
        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
        <span class="font-small">操作信息</span>
      </div>
      <el-table style="margin-top: 20px; width: 100%" height="100%" ref="orderHistoryTable" :data="order.historyList" border>
        <el-table-column label="操作者" width="120" align="center">
          <template #default="scope">
            {{ scope.row.operateMan }}
          </template>
        </el-table-column>
        <el-table-column label="操作时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="120" align="center">
          <template #default="scope">
            {{ ORDER_STATUS_DICT[scope.row.orderStatus] }}
          </template>
        </el-table-column>
        <el-table-column label="付款状态" width="120" align="center">
          <template #default="scope">
            {{ PAY_STATUS_DICT[scope.row.orderStatus] }}
          </template>
        </el-table-column>
        <el-table-column label="发货状态" width="120" align="center">
          <template #default="scope">
            {{ DELIVER_STATUS_DICT[scope.row.orderStatus] }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template #default="scope">
            {{ scope.row.note }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="修改收货人信息" v-model="receiverDialogVisible" width="40%">
      <el-form :model="receiverInfo" ref="receiverInfoForm" label-width="auto">
        <el-form-item label="收货人姓名：">
          <el-input v-model="receiverInfo.receiverName"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：">
          <el-input v-model="receiverInfo.receiverPhone"> </el-input>
        </el-form-item>
        <el-form-item label="邮政编码：">
          <el-input v-model="receiverInfo.receiverPostCode"> </el-input>
        </el-form-item>
        <el-form-item label="所在区域：">
          <v-distpicker
            :province="receiverInfo.receiverProvince"
            :city="receiverInfo.receiverCity"
            :area="receiverInfo.receiverRegion"
            @selected="onSelectRegion"
          ></v-distpicker>
        </el-form-item>
        <el-form-item label="详细地址：">
          <el-input v-model="receiverInfo.receiverDetailAddress" type="textarea" rows="3"> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="receiverDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateReceiverInfo">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="修改费用信息" v-model="moneyDialogVisible" width="40%">
      <div class="table-layout">
        <el-row>
          <el-col :span="6" class="table-cell-title">商品合计</el-col>
          <el-col :span="6" class="table-cell-title">运费</el-col>
          <el-col :span="6" class="table-cell-title">优惠券</el-col>
          <el-col :span="6" class="table-cell-title">积分抵扣</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">￥{{ order.totalAmount }}</el-col>
          <el-col :span="6" class="table-cell">
            <el-input v-model.number="moneyInfo.freightAmount" size="small">
              <template #prepend>￥</template>
            </el-input>
          </el-col>
          <el-col :span="6" class="table-cell">-￥{{ order.couponAmount }}</el-col>
          <el-col :span="6" class="table-cell">-￥{{ order.integrationAmount }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell-title">活动优惠</el-col>
          <el-col :span="6" class="table-cell-title">折扣金额</el-col>
          <el-col :span="6" class="table-cell-title">订单总金额</el-col>
          <el-col :span="6" class="table-cell-title">应付款金额</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">-￥{{ order.promotionAmount }}</el-col>
          <el-col :span="6" class="table-cell">
            <el-input v-model.number="moneyInfo.discountAmount" size="small"> <template #prepend>-￥</template></el-input>
          </el-col>
          <el-col :span="6" class="table-cell">
            <span class="color-danger">￥{{ orderTotal }}</span>
          </el-col>
          <el-col :span="6" class="table-cell">
            <span class="color-danger"> ￥{{ orderPayTotal }} </span>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="moneyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdateMoneyInfo">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="发送站内信" v-model="messageDialogVisible" width="40%">
      <el-form :model="message" ref="receiverInfoForm" label-width="auto">
        <el-form-item label="标题：">
          <el-input v-model="message.title"></el-input>
        </el-form-item>
        <el-form-item label="内容：">
          <el-input v-model="message.content" type="textarea" rows="3"> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="messageDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSendMessage">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="关闭订单" v-model="closeDialogVisible" width="40%">
      <el-form :model="closeInfo" label-width="auto">
        <el-form-item label="操作备注：">
          <el-input v-model="closeInfo.note" type="textarea" rows="3"> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCloseOrder">确 定</el-button>
      </template>
    </el-dialog>
    <el-dialog title="备注订单" v-model="markOrderDialogVisible" width="40%">
      <el-form :model="markInfo" label-width="auto">
        <el-form-item label="操作备注：">
          <el-input v-model="markInfo.note" type="textarea" rows="3"> </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="markOrderDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleMarkOrder">确 定</el-button>
      </template>
    </el-dialog>
    <logistics-dialog v-model="logisticsDialogVisible"></logistics-dialog>
  </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderDetail, updateReceiverInfo, updateMoneyInfo, closeOrder, updateOrderNote, deleteOrder } from '@/api/order'
import LogisticsDialog from './components/logisticsDialog.vue'
import { formatDateTime } from '@/utils/format'
// import VDistpicker from 'v-distpicker'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { Order, OrderMoneyInfoParams, OrderUpdateNoteParams, OrderUpdateReceiverInfoParams } from '@/models/order'
import { ORDER_TYPE_DICT, ORDER_STATUS_DICT, PAY_STATUS_DICT, DELIVER_STATUS_DICT, PAY_TYPE_DICT, ORDER_SOURCE_TYPE_DICT } from '@/constant'
import BigNumber from 'bignumber.js'

defineOptions({ name: 'OrderDetail' })
const route = useRoute()
const router = useRouter()
const order = ref<Order>({})
const receiverDialogVisible = ref(false)
const receiverInfo = ref<OrderUpdateReceiverInfoParams>({})
const moneyDialogVisible = ref(false)
const moneyInfo = ref<OrderMoneyInfoParams>({})
const messageDialogVisible = ref(false)
const message = ref({ title: null, content: null })
const closeDialogVisible = ref(false)
const closeInfo = ref<{ id?: number; note?: string }>({})
const markOrderDialogVisible = ref(false)
const markInfo = ref<{ id?: number; note?: string }>({})
const logisticsDialogVisible = ref(false)
const currentId = computed(() => Number(route.query.id))

const orderTotal = computed(() => new BigNumber(order.value.totalAmount || 0).plus(order.value.freightAmount || 0).toNumber())
const orderPayTotal = computed(() =>
  new BigNumber(order.value.payAmount || 0)
    .plus(order.value.freightAmount || 0)
    .minus(order.value.discountAmount || 0)
    .toNumber()
)
onMounted(async () => {
  const response = await getOrderDetail(currentId.value)
  order.value = response.data.data
})
function formatNull(value: any) {
  if (value === undefined || value === null || value === '') {
    return '暂无'
  } else {
    return value
  }
}
function formatLongText(value: any) {
  if (value === undefined || value === null || value === '') {
    return '暂无'
  } else if (value.length > 8) {
    return value.substr(0, 8) + '...'
  } else {
    return value
  }
}
function formatAddress() {
  let str = order.value.receiverProvince
  if (order.value.receiverCity != null) {
    str += '  ' + order.value.receiverCity
  }
  str += '  ' + order.value.receiverRegion
  str += '  ' + order.value.receiverDetailAddress
  return str
}

function formatProductAttr(value: any) {
  return JSON.parse(value || '[]').reduce((a: string, b: { key: string; value: string }) => `${a}${b.key}:${b.value};`, '')
}
function onSelectRegion(data: any) {
  receiverInfo.value.receiverProvince = data.province.value
  receiverInfo.value.receiverCity = data.city.value
  receiverInfo.value.receiverRegion = data.area.value
}
function showUpdateReceiverDialog() {
  receiverDialogVisible.value = true
  receiverInfo.value = {
    orderId: order.value.id,
    receiverName: order.value.receiverName,
    receiverPhone: order.value.receiverPhone,
    receiverPostCode: order.value.receiverPostCode,
    receiverDetailAddress: order.value.receiverDetailAddress,
    receiverProvince: order.value.receiverProvince,
    receiverCity: order.value.receiverCity,
    receiverRegion: order.value.receiverRegion,
    status: order.value.status,
  }
}
async function handleUpdateReceiverInfo() {
  await ElMessageBox.confirm('是否要修改收货信息?', '提示', { type: 'warning' })
  await updateReceiverInfo(receiverInfo.value)
  receiverDialogVisible.value = false
  ElMessage.success('修改成功!')
  const response = await getOrderDetail(currentId.value)
  order.value = response.data.data
}
function showUpdateMoneyDialog() {
  moneyDialogVisible.value = true
  moneyInfo.value.orderId = order.value.id
  moneyInfo.value.freightAmount = order.value.freightAmount
  moneyInfo.value.discountAmount = order.value.discountAmount
  moneyInfo.value.status = order.value.status
}
async function handleUpdateMoneyInfo() {
  await ElMessageBox.confirm('是否要修改费用信息?', '提示', { type: 'warning' })
  await updateMoneyInfo(moneyInfo.value)
  moneyDialogVisible.value = false
  ElMessage.success('修改成功!')
  const response = await getOrderDetail(currentId.value)
  order.value = response.data.data
}
function showMessageDialog() {
  messageDialogVisible.value = true
  message.value.title = null
  message.value.content = null
}
async function handleSendMessage() {
  await ElMessageBox.confirm('是否要发送站内信?', '提示', { type: 'warning' })
  messageDialogVisible.value = false
  ElMessage.success('发送成功')
}
function showCloseOrderDialog() {
  closeDialogVisible.value = true
  closeInfo.value.note = undefined
  closeInfo.value.id = currentId.value
}
async function handleCloseOrder() {
  await ElMessageBox.confirm('是否要关闭?', '提示', { type: 'warning' })
  let params = { ids: closeInfo.value.id + '', note: closeInfo.value.note + '' }
  await closeOrder(params)
  closeDialogVisible.value = false
  ElMessage.success('订单关闭成功')
  const response = await getOrderDetail(currentId.value)
  order.value = response.data.data
}
function showMarkOrderDialog() {
  markOrderDialogVisible.value = true
  markInfo.value.id = currentId.value
  markInfo.value.note = undefined
}
async function handleMarkOrder() {
  await ElMessageBox.confirm('是否要备注订单?', '提示', { type: 'warning' })
  let params = { id: markInfo.value.id, note: markInfo.value.note, status: order.value.status }
  await updateOrderNote(params)
  markOrderDialogVisible.value = false
  ElMessage.success('订单备注成功')
  const response = await getOrderDetail(currentId.value)
  order.value = response.data.data
}
async function handleDeleteOrder() {
  await ElMessageBox.confirm('是否要进行该删除操作?', '提示', { type: 'warning' })
  await deleteOrder({ ids: currentId.value + '' })
  ElMessage.success('删除成功')
  router.back()
}
function showLogisticsDialog() {
  logisticsDialogVisible.value = true
}
</script>
<style scoped>
.detail-container {
  width: 80%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
}

.operate-container {
  background: #f2f6fc;
  height: 80px;
  margin: -20px -20px 0;
  line-height: 80px;
}

.operate-button-container {
  float: right;
  margin-right: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
</style>
